import Vue from 'vue'
import VueResource from 'vue-resource'
import store from './store'
import message from './message'
import {
    fail
} from 'assert';

Vue.use(VueResource);

var apiHost = process.env.apiHost;


var common = {
    apiHost,
    EmptyFn: () => {}
};

// 引入vue的this
let VueThis = null

var importVueThis = function (t) {
    VueThis = t;
}


/**
 * 发送HTTP请求
 * @param {*} apiUrl 
 * @param {*} params 
 * @returns promise
 */
common.Send = function(apiUrl, params) {
    return Vue.http.post(`${apiHost}${apiUrl}`, params, {
        emulateJSON: true
    });
}

/**
 * 发送API请求
 * @param {string} apiUrl 
 * @param {json} params 
 * @param {function} okCb
 * @param {function} failCb
 */
common.Api = function(apiUrl, params, okCb, failCb) {
    console.log(`[API->]${apiUrl}`);
    console.log('[API Params]'+JSON.stringify(params));
    common.Send(apiUrl, params).then((res) => {
            console.log(`[API<-]${JSON.stringify(res.body)}`);
            var body = res.body;
            if (body.status == store.Codes.OK || body.code == store.Codes.OK) {
                if (okCb) {
                    if (body.data) {
                        okCb(body.data);
                    } else {
                        okCb(body);
                    }
                }

            } else {
                // if(body.status == store.Codes.ParamError){
                // alert(message.get(body.msg));
                // }
                body.msg = message.get(body.msg);
                if (failCb) {
                    failCb(body);
                }else{
                    VueThis.$toast(body.msg);
                }

            }
        })
        .catch((res) => {
            console.log(res);
            // alert('网络异常');
            if (failCb) {
                failCb({
                    msg: '网络异常',
                    status: store.Codes.NetworkCrash
                });
            }

        });
}

var Caches = {};

/**
 * 发送API请求，优先从缓存里面获取
 * 适合获取不更新的数据
 * @param {string} apiUrl 
 * @param {json} params 
 * @param {function} okCb
 * @param {function} failCb
 */
common.ApiWithCache = function(apiUrl, params, okCb, failCb) {
    var key = `${apiUrl}|${JSON.stringify(params)}`;
    if (Caches[key]) {
        okCb(Caches[key]);
        return;
    }
    common.Api(apiUrl, params, function(data) {
        Caches[key] = data;
        okCb(Caches[key]);
    }, failCb);
}

/**
 * 发送API请求，直接从服务器获取，并强制更新缓存
 * 适合更新数据后刷新缓存
 * @param {string} apiUrl 
 * @param {json} params 
 * @param {function} okCb
 * @param {function} failCb
 */
common.ApiWithCacheUpdate = function(apiUrl, params, okCb, failCb) {
    var key = `${apiUrl}|${JSON.stringify(params)}`;
    common.Api(apiUrl, params, function(data) {
        Caches[key] = data;
        okCb(Caches[key]);
    }, failCb);

}

/**
 * 获取请求参数
 * @param {*} name 
 */
common.getParam = function(name){
    var ps={}; 
    var ts = location.search.split(/[\?|&]/g); 
    for(var i in ts){ 
        var a = ts[i]; 
        if(!a) continue; 
        var ss = a.split('='); 
        ps[ss[0]] = decodeURIComponent(ss[1]); 
    } 
    return ps[name]; 
}

export default common

export {importVueThis}